<template>
  <div v-has="'dept-query'" class="user-manager">
    <div class="query-form">
      <query-form
        :form="searchForm"
        v-model="deptForm"
        @handleQuery="handleQuery"
        @handleReset="handleReset"
      />
      <!-- <el-form
        :model="deptForm"
        label-width="120px"
        ref="query_form"
        style="display: flex"
      >
        <div class="query" style="display: flex">
          <el-form-item label="部门名称" prop="deptName">
            <el-input
              v-model="deptForm.deptName"
              placeholder="请输入部门名称"
            />
          </el-form-item>
        </div>

        <div class="clickQuery" style="margin-left: 30px; width: 200px">
          <el-button type="primary" @click="screening">查询</el-button>
          <el-button @click="query_reset">重置</el-button>
        </div>
      </el-form> -->
    </div>

    <div class="base-table">
      <list-table
        :columns="columns"
        :tableList="deptList"
        :btnList="btnList"
        @userCreate="userCreate"
        @onuserEdit="onuserEdit"
        @userDel="userDel"
      />
      <pagination :total="total" @handleCurrentChange="handleCurrentChange" />
      <!-- <div class="action">
        <el-button type="primary" v-has="'dept-create'" @click="deptAdd"
          >创建</el-button
        >
      </div>

      <el-table
        ref="multipleTableRef"
        :data="deptList"
        style="width: 100%"
        row-key="_id"
        :tree-props="{ children: 'children' }"
      >
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
        ></el-table-column>

        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button
              type="primary"
              @click="deptEdit(scope.row)"
              v-show="scope.row.parentId[0] != null"
              v-has="'dept-edit'"
              >编辑</el-button
            >
            <el-popconfirm
              confirm-button-text="Yes"
              cancel-button-text="No"
              title="Are you sure to delete?"
              @confirm="deptDel(scope.row)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  v-show="scope.row.parentId[0] != null"
                  v-has="'dept-delete'"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="page">
        <el-pagination
          layout=" prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div> -->
    </div>

    <el-dialog v-model="showMadol" :title="title">
      <el-form ref="dialogDeptForm" :model="deptForm" :rules="rules">
        <el-form-item label="上级部门" prop="parentId">
          <el-cascader
            v-model="deptForm.parentId"
            :options="deptList"
            :props="{
              checkStrictly: true,
              value: '_id',
              label: 'deptName',
            }"
            clearable
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="deptForm.deptName" autocomplete="off" />
        </el-form-item>

        <el-form-item label="负责人" prop="userName">
          <el-select
            v-model="deptForm.userName"
            class="m-2"
            placeholder="Select"
            @change="selectChange"
          >
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.userName"
              :value="`${item.userId}/${item.userName}/${item.userEmail}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人邮箱">
          <el-input v-model="Email" disabled autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import api from './../api'
import utils from './../utils/utils.js'
import message from '../utils/message.js'
import { ref, reactive, toRaw, nextTick } from 'vue'
// 显示搜索表单
const searchForm = [
  {
    type: 'input',
    label: '部门名称',
    prop: 'deptName',
    placeholder: '请输入部门名称'
  },
]
// 显示按钮
let btnList = reactive({
  tbTopBtn: [
    {
      type: 'primary',
      text: '创建',
      id: 1,
      has: 'user-create',
    },
  ],
  tableBtn: [
    {
      type: '',
      text: '编辑',
      id: 3,
    },
    {
      type: 'danger',
      text: '删除',
      id: 2,
    },
  ],
})
// 定义页面页码
let total = ref(1)
// 定义记录用户行为
let action = ref('create')
// 定义弹窗显示
let showMadol = ref(false)
// 定义弹窗标题
let title = ref('创建部门')
// 定义弹窗表单节点
const dialogDeptForm = ref(null)
// 弹窗表单校验
let rules = reactive({
  deptName: [
    {
      required: true,
      message: "请填写部门",
      trigger: "blur",
    }
  ],
  userName: [
    {
      required: true,
      message: "请选择负责人",
      trigger: "blur",
    },
  ],
})
// 定义请求列表
let deptForm = reactive({
  parentId: [null],
})
// 定义初始化的分页设置
let pager = reactive({
  pageNum: 1,
  pageSize: 10
})
// 定义角色列表
let deptList = ref([])
// 定义用户列表
let userList = ref([])
// 定义动态表格--格式
let columns = reactive([
  {
    label: '部门名称',
    prop: 'deptName'
  },
  {
    label: '负责人',
    prop: 'userName'
  },
  {
    label: '更新时间',
    prop: 'updateTime',
    formatter: (row, colum, value) => {
      return utils.formateDate(new Date(value))
    }
  },
  {
    label: '创建时间',
    prop: 'createTime',
    formatter: (row, colum, value) => {
      return utils.formateDate(new Date(value))
    }
  }
])
// 定义选中用户邮箱
let Email = ref(null)
// 创建弹窗选中值变化
const selectChange = (val) => {
  let [userId, userName, userEmail] = val.split("/")
  Email.value = userEmail
}

// 获取用户列表请求
const getUsersList = async () => {
  let data = { ...deptForm, ...pager }
  let { list, page } = await api.getUsersList(data)
  userList.value = list
}
// 定义部门请求
const getDeptList = async () => {
  api.getDeptList().then(res => {
    deptList.value = res
    console.log(res);
    total.value = res.length
  })
}
getDeptList()
getUsersList()
// 表单重置
const resetForm = () => {
  dialogDeptForm.value.resetFields()
}
// 创建
const userCreate = () => {
  showMadol.value = !showMadol.value
}
// 弹窗取消
const handleCancel = () => {
  resetForm()
  showMadol.value = !showMadol.value
}
//弹窗确定
const handleSubmit = () => {
  let [userId, userName] = deptForm.userName.split("/")
  deptForm.userId = userId
  deptForm.userName = userName
  dialogDeptForm.value.validate((vaild) => {
    if (vaild) {
      let data = toRaw(deptForm)
      data.action = action.value
      api.postDeptOperate(data).then(res => {
        showMadol.value = !showMadol.value
        message.message('提交成功!', 'success')
        resetForm()
        getDeptList()
      })
    }
  })
}
// 编辑
const onuserEdit = (row) => {
    if (row.row.parentId[0] != null) {
        title.value = '编辑部门'
        action.value = 'edit'
        showMadol.value = !showMadol.value
        nextTick(() => {
            Object.assign(deptForm, row.row)
        })
    }else{
        message.message('禁止操作!', 'error')
    }
}
// 删除
const userDel = (row) => {
  if (row.parentId[0] != null) {
        action.value = 'delete'
        let data = { _id: row._id, action: action.value }
        api.postDeptOperate(data).then(res => {
            message.message('删除成功!', 'success')
            getDeptList()
        })
  }else{
        message.message('禁止操作!', 'error')

  }
}
// 查询
const handleQuery = (val) => {
  let data = {
    deptName: val.value.deptName
  }
  api.getDeptList(data).then(res => {
    deptList.value = res
    message.message('查询成功!', 'success')
  })
}
// 重置
const handleReset = (val) => { message.message('重置成功!', 'success') }
// 定义页面列表切换事件
const handleCurrentChange = async (val) => {
  let data = { ...deptForm, ...pager }
  data.pageNum = val
  let { list, page } = await api.getUsersList(data)
  userList.value = list
}
</script>

<style lang="scss" scoped>
.user-manager {
  .query-form {
    border-radius: 5px;
    background-color: #fff;
    padding: 20px;
    .el-form-item {
      margin-bottom: 0;
    }
  }
  .base-table {
    margin-top: 20px;
    border-radius: 5px;
    .action {
      padding: 20px;
      background-color: #fff;
      border-bottom: 1px solid #eef0f3;
    }
    .page {
      margin: 10px auto;
      float: right;
    }
  }
}
</style>